<template>
  <PageWrapper title="专利申请趋势分析" contentFullHeight>
    <CollapseContainer title="查询条件">
      <a-form layout="inline" :model="queryForm" class="query-form">
        <a-row :gutter="[16, 16]" style="width: 100%;">
          <a-col :span="8">
            <a-form-item label="技术分类" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
              <a-select
                v-model:value="queryForm.selectedTechnologies"
                mode="multiple"
                placeholder="请选择技术分类（可多选）"
                :options="technologyOptions"
                :fieldNames="{ label: 'name', value: 'id' }"
                showSearch
                :filter-option="filterTechnology"
                allowClear
                :max-tag-count="2"
              >
              </a-select>
            </a-form-item>
          </a-col>
          
          <a-col :span="6">
            <a-form-item label="开始年份" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
              <a-select
                v-model:value="queryForm.startYear"
                placeholder="开始年份"
                :options="yearOptions"
              />
            </a-form-item>
          </a-col>
          
          <a-col :span="6">
            <a-form-item label="结束年份" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
              <a-select
                v-model:value="queryForm.endYear"
                placeholder="结束年份"
                :options="yearOptions"
              />
            </a-form-item>
          </a-col>
          
          <a-col :span="4">
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="handleQuery" :loading="loading">
                  <template #icon><SearchOutlined /></template>
                  加载数据
                </a-button>
                <a-button @click="handleReset">
                  <template #icon><ReloadOutlined /></template>
                  重置
                </a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="[16, 16]" style="width: 100%; margin-top: 8px;">
          <a-col :span="8">
            <a-form-item label="图表类型" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
              <a-radio-group v-model:value="queryForm.chartType" button-style="solid">
                <a-radio-button value="line">折线图</a-radio-button>
                <a-radio-button value="bar">柱状图</a-radio-button>
                <a-radio-button value="mixed">混合图</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </CollapseContainer>

    <CollapseContainer title="趋势图表" v-show="chartData.length > 0">
      <div class="chart-container">
        <div ref="chartRef" style="width: 100%; height: 600px;"></div>
      </div>
      
      <!-- 统计信息 -->
      <a-row :gutter="16" class="statistics" v-if="statisticsData.length > 0">
        <a-col :span="6" v-for="stat in statisticsData" :key="stat.technologyId">
          <a-statistic
            :title="stat.technologyName"
            :value="stat.totalCount"
            :value-style="{ color: stat.color }"
          >
            <template #suffix>件</template>
          </a-statistic>
        </a-col>
      </a-row>
    </CollapseContainer>

    <!-- 空状态 -->
    <div class="empty-state" v-show="!loading && chartData.length === 0">
      <a-empty description="请选择技术分类并点击加载数据">
        <a-button type="primary" @click="handleQuery" :disabled="queryForm.selectedTechnologies.length === 0">
          立即查询
        </a-button>
      </a-empty>
    </div>
  </PageWrapper>
</template>

<script lang="ts" name="trend-analysis" setup>
import { ref, reactive, onMounted, nextTick, computed, type Ref } from 'vue';
import { PageWrapper } from '/@/components/Page';
import { CollapseContainer } from '/@/components/Container';
import { useMessage } from '/@/hooks/web/useMessage';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import { useECharts } from '/@/hooks/web/useECharts';
import type { EChartsOption } from 'echarts';

import { getAllTechnologyList, getTechnologyTrend } from './TrendAnalysis.api';
import type { 
  TechnologyItem, 
  TrendQueryParams, 
  TechnologyTrendData, 
  TrendQueryResult,
  ChartSeries 
} from './TrendAnalysis.data';

// JeecG 消息提示工具
const { createMessage } = useMessage();

// 响应式数据
const loading = ref(false);
const chartRef = ref<HTMLDivElement>();
const technologyOptions = ref<TechnologyItem[]>([]);
const chartData = ref<TechnologyTrendData[]>([]);

// 查询表单
const queryForm = reactive<TrendQueryParams>({
  selectedTechnologies: [],
  startYear: 2010,
  endYear: new Date().getFullYear(),
  chartType: 'line'
});

// 年份选项（2010年到当前年份）
const yearOptions = computed(() => {
  const currentYear = new Date().getFullYear();
  const options: Array<{ label: string; value: number }> = [];
  for (let year = 2010; year <= currentYear; year++) {
    options.push({ label: `${year}年`, value: year });
  }
  return options.reverse(); // 最新年份在前
});

// 统计数据
const statisticsData = ref<Array<{
  technologyId: string;
  technologyName: string;
  totalCount: number;
  color: string;
}>>([]);

// 图表颜色配置
const chartColors = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#13c2c2', '#eb2f96', '#fa8c16'];

// 初始化图表
const { setOptions: setChartOptions, getInstance: getChartInstance } = useECharts(chartRef as Ref<HTMLDivElement>);

// 技术选项过滤
const filterTechnology = (input: string, option: any) => {
  return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

// 加载技术分类列表
const loadTechnologyList = async () => {
  try {
    const result = await getAllTechnologyList();
    if (result && result.length > 0) {
      technologyOptions.value = result;
    }
  } catch (error) {
    console.error('加载技术分类失败:', error);
    createMessage.error('加载技术分类失败');
  }
};

// 查询趋势数据
const handleQuery = async () => {
  if (queryForm.selectedTechnologies.length === 0) {
    createMessage.warning('请至少选择一个技术分类');
    return;
  }

  if (queryForm.startYear > queryForm.endYear) {
    createMessage.warning('开始年份不能大于结束年份');
    return;
  }

  loading.value = true;
  
  try {
    const params = {
      technologyIds: queryForm.selectedTechnologies,
      startYear: queryForm.startYear,
      endYear: queryForm.endYear
    };
    
    const result: TrendQueryResult = await getTechnologyTrend(params);
    
    if (result && result.trendDataList) {
      chartData.value = result.trendDataList;
      generateStatistics();
      await nextTick();
      renderChart();
      createMessage.success(`成功加载 ${result.trendDataList.length} 个技术分类的趋势数据`);
    } else {
      chartData.value = [];
      createMessage.info('未查询到相关数据');
    }
  } catch (error: any) {
    console.error('查询趋势数据失败:', error);
    createMessage.error('查询失败：' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
};

// 生成统计数据
const generateStatistics = () => {
  statisticsData.value = chartData.value.map((item, index) => ({
    technologyId: item.technologyId,
    technologyName: item.technologyName,
    totalCount: item.totalCount,
    color: chartColors[index % chartColors.length]
  }));
};

// 渲染图表
const renderChart = () => {
  if (!chartData.value.length) return;

  // 生成年份数组
  const years: number[] = [];
  for (let year = queryForm.startYear; year <= queryForm.endYear; year++) {
    years.push(year);
  }

  // 生成系列数据
  const series: ChartSeries[] = chartData.value.map((item, index) => {
    const data = years.map(year => {
      const yearData = item.yearDataList.find(d => d.year === year);
      return yearData ? yearData.count : 0;
    });

    return {
      name: item.technologyName,
      type: queryForm.chartType === 'mixed' ? (index % 2 === 0 ? 'bar' : 'line') : queryForm.chartType,
      data,
      smooth: queryForm.chartType === 'line',
      itemStyle: {
        color: chartColors[index % chartColors.length]
      },
      lineStyle: queryForm.chartType === 'line' ? {
        width: 3
      } : undefined
    };
  });

  const option: EChartsOption = {
    title: {
      text: '专利申请趋势分析',
      left: 'center',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function (params: any) {
        let html = `<div><strong>${params[0].axisValue}年</strong></div>`;
        params.forEach((param: any) => {
          html += `<div style="margin: 2px 0;">
            <span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:${param.color}"></span>
            ${param.seriesName}: <strong>${param.value}</strong> 件
          </div>`;
        });
        return html;
      }
    },
    legend: {
      top: '10%',
      type: 'scroll'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '20%',
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: { 
          title: '保存图片',
          name: '专利申请趋势图'
        },
        dataZoom: {
          title: {
            zoom: '区域缩放',
            back: '区域缩放还原'
          }
        },
        restore: { title: '还原' }
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: queryForm.chartType === 'bar',
      data: years,
      name: '年份',
      nameLocation: 'middle',
      nameGap: 30
    },
    yAxis: {
      type: 'value',
      name: '专利数量（件）',
      nameLocation: 'middle',
      nameGap: 50,
      minInterval: 1
    },
    series: series as any,
    dataZoom: [
      {
        type: 'slider',
        show: years.length > 10,
        xAxisIndex: 0,
        start: 0,
        end: 100
      }
    ]
  };

  setChartOptions(option);
};

// 重置表单
const handleReset = () => {
  queryForm.selectedTechnologies = [];
  queryForm.startYear = 2010;
  queryForm.endYear = new Date().getFullYear();
  queryForm.chartType = 'line';
  chartData.value = [];
  statisticsData.value = [];
  
  const chartInstance = getChartInstance();
  if (chartInstance) {
    chartInstance.clear();
  }
};

// 页面初始化
onMounted(() => {
  loadTechnologyList();
});
</script>

<style scoped lang="less">
.query-form {
  .ant-form-item {
    margin-bottom: 16px;
  }
}

.chart-container {
  width: 100%;
  margin-bottom: 24px;
}

.statistics {
  margin-top: 24px;
  padding: 20px;
  background: #fafafa;
  border-radius: 6px;
  
  .ant-statistic {
    text-align: center;
  }
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

:deep(.ant-select-selector) {
  min-height: 32px;
}

:deep(.ant-radio-button-wrapper) {
  height: 32px;
  line-height: 30px;
}
</style>
